require('chromedriver');
let chrome = require('selenium-webdriver/chrome');
const webDriver = require('selenium-webdriver'),
    By = webDriver.By;
const options = new chrome.Options();
// 隐藏窗口
options.addArguments('headless');
options.addArguments('no-sandbox')
options.addArguments('disable-dev-shm-usage')
const driver = new webDriver.Builder()
    .forBrowser('chrome')
    .setChromeOptions(options)
    .build();
const request = require('request-promise');
const { waitTime } = require('../common');
const fs = require('fs');
const _ = require('lodash');

const getParcelUrl = 'https://www.colissimo.fr/entreprise/colis/parcels/search';
const Cookie = 'JSESSIONID_OSC=1B251755BB8C702D4F6CB4BFC54E5011.tc-osc-NODEV3; user=eyJhbGciOiJSUzI1NiJ9.eyJzdWIiOiJ7XCJpbnRlcm5hbFwiOlwiZmFsc2VcIixcIm1haW5BY2NvdW50XCI6XCI5NjYwMzZcIixcImFkbWluXCI6ZmFsc2UsXCJwYXJ0ZW5haXJlXCI6XCJmYWxzZVwiLFwiY2F0ZWdvcnlcIjpcIlBPUlRBSUxfRU5UUkVQUklTRVwiLFwibG9naW5cIjpcInNhdjk2NjAzNlwiLFwidXNlcktleVwiOlwiXCIsXCJzaWRcIjpcImRlMWJkZjlhYTk0ZmQ3MGU2MmNjNjMwOGQ1NDlkYzU2XCJ9In0.nCwFlt7-mzVl9_Ah-sk0xNdVO0nb-TN1tNxcu2Oet4s5YZJsDC4JkIbeP_7f3sg__S4PnsCMmiR32NlAyOs06C7sTpr22NW5XPfK5DIxGbEX-F-RVCpDiz716I0uaiwRs0kk5X52RAHRg9bJ4MSz87VGs3y5GAU5MJnwutLfnbHbCS3Ku891OvdFmv0ecP0JIHuV3Mc1AtZkRtTsAHV0RUe0jeIFdlyFuwu1uF-VBeXQ6b9DXPiP4l8J-Rb64CpxhKV-l0kXxt3y5z7FT1WpqCwYq9wNL1VzI7Bsv79N5L3JbkAP6lknt7_ZpJrFupLrO1IUT59aF0kPt6UehLCPAw; atidvisitor=%7B%22name%22%3A%22atidvisitor%22%2C%22val%22%3A%7B%22vrn%22%3A%22-593872-%22%7D%2C%22options%22%3A%7B%22path%22%3A%22%2F%22%2C%22session%22%3A15724800%2C%22end%22%3A15724800%7D%7D';
const trackingNumbers = [
    '6A20401031908',
    '6A20401073243',
    '6A20411609517',
    '6A20535978612',
    '6A20570430731',
];

async function getParcels(trackingNumbers, Cookie) {
   const result = await request({
       uri: getParcelUrl,
       method: 'POST',
       headers: {
           Cookie
       },
       json: true,
       body: {
           "accounts": [
               966036
           ],
           "page": 1,
           "resultPerPage": 1000,
           "searchQuery": [
               {
                   "criteria": "parcel_ref",
                   "value": trackingNumbers
               }
           ]
       }
   });
   console.log(`getParcels done, size ${_.size(result.parcels)}`);
   const claims = await getClaimsByParcelUuid(_.map(result.parcels, parcel => { return parcel.parcelUuid; }));
   console.log(`get claims done`);
   const obj = _.transform(claims, (result, value) => {
       result[value.parcelUuid] = value.claimUuid;
       return result;
   }, {});
   return result.parcels.map(parcel => {
       return {
           uuid: parcel.parcelUuid,
           trackingNumber: parcel.parcelReference,
           claims: obj[parcel.parcelUuid]
       };
   });
}

async function getClaimsByParcelUuid(parcelUuids) {
    return await request({
        uri: 'https://www.colissimo.fr/entreprise/colis/claim/claimsByParcelUuid',
        method: 'POST',
        headers: {
            Cookie
        },
        json: true,
        body: parcelUuids
    });
}

async function login(driver, By, max = false, width = 1200, height = 700) {
    console.log('login start');
    if (max) {
        await driver.manage().window().maximize();
    } else {
        await driver.manage().window().setRect({width, height, x: 0, y: 0});
    }
    await driver.get('https://www.colissimo.entreprise.laposte.fr/fr');
    await waitTime(2000);
    await driver.findElement(By.id('identifier')).sendKeys('sav966036');
    await driver.findElement(By.id('password')).sendKeys('sav966036import');
    await driver.findElement(By.id('validButtonLogin')).click();
    await waitTime(3000);
}


async function getHistory() {
    const parcels = await getParcels(trackingNumbers, Cookie);
    await login(driver, By, true);
    await waitTime(1000);
    await driver.findElement(By.xpath('//*[@id="divApplis"]/div[1]/a[2]/span')).click();
    await waitTime(1000);
    const handlers = await driver.getAllWindowHandles();
    await driver.switchTo().window(handlers[1]);
    for (let parcel of parcels) {
        await driver.get(`https://www.colissimo.fr/entreprise/colis/resources/#/customer-service/request?parcelUuid=${parcel.uuid}&claimUuid=${parcel.claims}`);
        await waitTime(1500);
        driver.takeScreenshot().then((image, err) => {
            if (err) {
                console.error(JSON.stringify(err));
            }
            fs.writeFile(`../file/colissimo/${parcel.trackingNumber}.png`, image, 'base64',  (err) => {
                if (err) {
                    console.error(JSON.stringify(err));
                } else {
                    console.log(`${parcel.trackingNumber} done`);
                }
            });
        });
        await waitTime(1000);
    }
}


// const detailUrl = 'https://www.colissimo.fr/entreprise/colis/resources/#/parcel-tracking/parcel?parcelUuid=34743a85-8446-3645-b21c-dcb4bec96fd8';
async function play() {
    const parcels = await getParcels(trackingNumbers, Cookie);
    await login(driver, By)
    await waitTime(1000);
    await driver.findElement(By.xpath('//*[@id="divApplis"]/div[1]/a[2]/span')).click();
    await waitTime(1000);
    const handlers = await driver.getAllWindowHandles();
    await driver.switchTo().window(handlers[1]);
    for (let parcel of parcels) {
        await driver.get(`https://www.colissimo.fr/entreprise/colis/resources/#/parcel-tracking/parcel?parcelUuid=${parcel.uuid}`);
        await waitTime(1500);
        driver.takeScreenshot().then((image, err) => {
            if (err) {
                console.error(JSON.stringify(err));
            }
            fs.writeFile(`../file/colissimo/${parcel.trackingNumber}.png`, image, 'base64',  (err) => {
                if (err) {
                    console.error(JSON.stringify(err));
                } else {
                    console.log(`${parcel.trackingNumber} done`);
                }
            });
        });
        await waitTime(1000);
    }
}

play().then(() => {
    console.log('截图完成');
})
